package cc.lirns.demo.websocket.withspring.handler;

import cc.lirns.utils.result.ResultUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.WebSocketMessage;
import org.springframework.web.socket.WebSocketSession;

import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 具体的某个连接的处理方法
 *
 * @author lirns
 * @date 2021/12/2 16:22
 */
@Slf4j
@Component
public class MyWsHandle extends MyWebSocketUtil {

    /**
     * 记录当前在线连接数
     */
    private static final AtomicInteger ONLINE_COUNT = new AtomicInteger(0);

    /**
     * onopen
     */
    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        ONLINE_COUNT.incrementAndGet(); // 在线数加1
    }

    /**
     * onmessage
     */
    @Override
    public void handleMessagePost(WebSocketSession session, WebSocketMessage<?> message, Map maps) throws Exception {
        log.debug(this.getClass().getSimpleName() + " handleMessagePost");
        String mapKey = "flag";
        String event = "event";
        if (event.equalsIgnoreCase(maps.get(mapKey).toString())) {
            sendMessage(session, ResultUtil.success(), event);
            return;
        }
    }

    /**
     * onerror
     */
    @Override
    public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {
        log.error("异常原因{}", exception.getMessage(), exception);
    }

    /**
     * onclose
     */
    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
        log.debug("ws关闭，关闭原因{}", status.getReason());
        ONLINE_COUNT.decrementAndGet(); // 在线数减1
    }

}
